<template>
  
  <div class="traceable-page">
    <el-row :gutter="16">
      <el-col :span="18">
        <!-- 商品信息 -->
        <el-card class="mb16 header-card" shadow="never">
          <div class="header-wrap">
            <div class="header-actions">
             
            </div>
           
            <el-image :src="fullImageUrl.fullImageUrl" fit="cover" class="cover" />
           
            <div class="meta">
              <div class="title-row">
                <h2 class="title">{{ product?.goodsName }}</h2>
              </div>
              
              <div class="header-meta-grid">

                <div class="kv"><span class="kv-label">生产批次：</span><span class="kv-value">   {{ product?.basicBatch
                    }}</span>
                </div>
                <div class="kv"><span class="kv-label">保质期：</span><span class="kv-value">{{ product?.basicExpiration }}
                    天</span></div>
                <div class="kv"><span class="kv-label">生产许可证号：</span><span class="kv-value">{{ product?.basicLicense
                    }}</span>
                </div>
                <div class="kv"><span class="kv-label">生产企业：</span><span class="kv-value">{{ product?.basicEnterprise
                    }}</span>
                </div>
              </div>
             
              {{ file?.url }}
              <!-- 产品检验报告上传区域 -->
              <div class="mt12">
                <div class="section-head inline">
                  <span class="blue-bar" />
                  <span>产品检验报告</span>
                </div>

                <!-- 检验报告上传组件：支持多图上传、预览、删除 -->
                <el-upload class="uploader mt8" action="#" list-type="picture-card" v-model:file-list="inspectFileList"
                  :http-request="(o) => uploadImage(o, 'inspect')" :on-remove="(f, l) => onRemove(f, l, 'inspect')"
                  :limit="MAX_IMAGES" :on-exceed="onExceed">

                  <el-icon> 
                    <Plus />
                  </el-icon>
                  <!-- 移除图片 -->

                  <template #file="{ file }">
                    <div class="upload-card">
                      <img class="upload-card-img" :src="file.url" alt="" />
                      <button class="delete-badge" @click.stop="removeFile('inspect', file, file.name)">×</button>
                    </div>
                  </template>
                </el-upload>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 顶部 tabs（只读） -->
        <el-card shadow="never" class="body-card">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="养殖信息" name="breed">
              <div class="section">
                <div class="section-head">
                  <span class="blue-bar" />
                  <span>养殖信息</span>
                  <button class="pill-button" @click="openBreedDialog">设置</button>
                </div>

                <div class="kv-grid">
                  <div class="kv"><span class="kv-label">品种：</span><span class="kv-value">{{ breed?.cultivationVariety
                      }}</span>
                  </div>
                  <div class="kv"><span class="kv-label">来源：</span><span class="kv-value">{{ breed?.cultivationSource
                      }}</span>
                  </div>
                  <div class="kv"><span class="kv-label">饲养天数：</span><span class="kv-value">{{ breed?.cultivationDays
                      }}</span>
                  </div>
                  <div class="kv"><span class="kv-label">饲养品牌：</span><span class="kv-value">{{ breed?.cultivationBrand
                      }}</span>
                  </div>
                  <div class="kv"><span class="kv-label">饲养负责人：</span><span class="kv-value">{{
                    breed?.cultivationLeader }}</span>
                  </div>
                  <div class="kv"><span class="kv-label">出栏日期：</span><span class="kv-value">{{
                    breed?.cultivationOutDate ? moment(breed?.cultivationOutDate).format("yyyy-MM-DD") : ""
                      }}</span>
                  </div>
                </div>
              </div>

              <!-- 保健信息 -->
              <div class="section mt16">
                <div class="section-head">
                  <span class="blue-bar" />
                  <span>保健信息</span>
                  <button class="pill-button" @click="addHealthRow">新增行</button>
                </div>
                <el-table :data="healthList" border style="width: 100%; margin-top: 12px">
                  <el-table-column prop="days" label="饲养天数" width="140">
                    <template #default="{ row }">
                      <template v-if="row.editing">
                        <el-input v-model="row.edit.days" maxlength="5" placeholder="数字，最多5位" />
                      </template>
                      <template v-else>{{ row.days }}</template>
                    </template>
                  </el-table-column>
                  <el-table-column prop="healthWay" label="保健方式">
                    <template #default="{ row }">
                      <template v-if="row.editing">
                        <el-input v-model="row.edit.healthWay" maxlength="30" placeholder="中文/字母/数字，≤30位" />
                      </template>
                      <template v-else>{{ row.healthWay }}</template>
                    </template>
                  </el-table-column>
                  <el-table-column prop="healthAction" label="保健方法">
                    <template #default="{ row }">
                      <template v-if="row.editing">
                        <el-input v-model="row.edit.healthAction" maxlength="30" placeholder="中文/字母/数字，≤30位" />
                      </template>
                      <template v-else>{{ row.healthAction }}</template>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="180">
                    <template #default="{ $index, row }">
                      <template v-if="!row.editing">
                        <el-button link size="small" type="primary" @click="editHealthRow($index)">修改</el-button>
                        <el-button link size="small" type="primary"
                          @click="removeHealthRow($index, row.id)">删除</el-button>
                      </template>
                      <template v-else>
                        <el-button link size="small" type="primary" @click="saveHealthRow($index, row)">保存</el-button>
                        <el-button link size="small" type="primary" @click="cancelHealthRow($index)">取消</el-button>
                      </template>
                    </template>
                  </el-table-column>
                </el-table>
              </div>

              <div class="section mt16">
                <div class="section-head">
                  <span class="blue-bar" />
                  <span>动检证</span>
                </div>
                <el-upload class="uploader mt8" action="#" list-type="picture-card" v-model:file-list="certFileList"
                  :http-request="(o) => uploadImage(o, 'cert')" :on-remove="(f, l) => onRemove(f, l, 'cert')"
                  :limit="MAX_IMAGES" :on-exceed="onExceed">
                  <el-icon>
                    <Plus />
                  </el-icon>
                  <template #file="{ file }">
                    <div class="upload-card">
                      <img class="upload-card-img" :src="file.url" alt="" />
                      <button class="delete-badge" @click.stop="removeFile('cert', file, file.name)">×</button>
                    </div>
                  </template>
                </el-upload>
              </div>

              <div class="section mt16">
                <div class="section-head">
                  <span class="blue-bar" />
                  <span>企业信息</span>
                  <button class="pill-button" @click="openFarmDialog">设置</button>
                </div>

                <div class="kv-grid">
                  <div class="kv"><span class="kv-label">养殖场：</span><span class="kv-value">{{ farmInfo?.enterpriseFarms
                      }}</span></div>
                  <div class="kv"><span class="kv-label">负责人：</span><span class="kv-value">{{ farmInfo?.enterpriseLeader
                      }}</span>
                  </div>
                  <div class="kv"><span class="kv-label">存栏数量（只）：</span><span class="kv-value">{{
                    farmInfo?.enterpriseNum
                      }}</span>
                  </div>
                </div>
              </div>

              <!-- 企业图片上传区域 -->
              <div class="section mt16">
                <div class="section-head">
                  <span class="blue-bar" />
                  <span>企业图片</span>
                </div>
                <el-upload class="uploader mt8" action="#" list-type="picture-card" v-model:file-list="companyFileList"
                  :http-request="(o) => uploadImage(o, 'company')" :on-remove="(f, l) => onRemove(f, l, 'company')"
                  :limit="MAX_IMAGES" :on-exceed="onExceed">
                  <el-icon>
                    <Plus />
                  </el-icon>
                  <template #file="{ file }">
                    <div class="upload-card">
                      <img class="upload-card-img" :src="file.url" alt="" />
                      <button class="delete-badge" @click.stop="removeFile('inspect', file, file.name)">×</button>
                    </div>
                  </template>
                </el-upload>
              </div>
            </el-tab-pane>

            <el-tab-pane label="屠宰信息" name="slaughter">
              <div class="section">
                <div class="section-head">
                  <span class="blue-bar" />
                  <span>屠宰信息</span>
                  <button class="pill-button" @click="openSlaughterDialog">设置</button>
                </div>

                <div class="kv-grid">
                  <div class="kv"><span class="kv-label">批次：</span><span class="kv-value">{{ slaughter?.slaughterBatch
                  }}</span>
                  </div>
                  <div class="kv"><span class="kv-label">到厂均重：</span><span class="kv-value"
                      v-if="slaughter?.slaughterWeight">{{
                        slaughter?.slaughterWeight
                      }}
                      公斤</span>
                  </div>
                  <div class="kv"><span class="kv-label">到厂时间：</span><span class="kv-value">{{
                    slaughter?.arrivaltime ? moment(slaughter?.arrivaltime).format("yyyy年MM月DD日 HH:mm:ss") : ""
                      }}</span>
                  </div>
                  <div class="kv"><span class="kv-label">屠宰时间：</span><span class="kv-value">{{
                    slaughter?.slaughtertime ? moment(slaughter?.slaughtertime).format("yyyy年MM月DD日 HH:mm:ss") : ""
                  }}</span>
                  </div>
                </div>
              </div>

              <!-- 屠宰相关资质上传区域 -->
              <div class="section mt16">
                <div class="section-head">
                  <span class="blue-bar" />
                  <span>相关资质</span>
                </div>
                <el-upload class="uploader mt8" action="#" list-type="picture-card"
                  v-model:file-list="slaughterCertList" :http-request="(o) => uploadImage(o, 'slaughterCert')"
                  :on-remove="(f, l) => onRemove(f, l, 'slaughterCert')" :limit="MAX_IMAGESs" :on-exceed="onExceed">
                  <el-icon>
                    <Plus />
                  </el-icon>
                  <template #file="{ file }">
                    <div class="upload-card">
                      <img class="upload-card-img" :src="file.url" alt="" />
                      <div class="img-bottom-label">{{ file.label || '资质' }}</div>
                      <button class="delete-badge" @click.stop="removeFile('inspect', file, file.name)">×</button>
                    </div>
                  </template>
                </el-upload>
              </div>

              <div class="section mt16">
                <div class="section-head">
                  <span class="blue-bar" />
                  <span>企业信息</span>
                  <button class="pill-button" @click="openProcessCompanyDialog(company?.seAddress)">设置</button>
                </div>
                <div class="kv-grid">
                  <div class="kv"><span class="kv-label">公司名称：</span><span class="kv-value">{{ company?.slaughterName
                  }}</span>
                  </div>
                  <div class="kv"><span class="kv-label">成立时间：</span><span class="kv-value">{{
                    company?.time ? moment(company?.time).format("yyyy年MM月DD日") : ""
                  }}</span>
                  </div>
                  <div class="kv col-2"><span class="kv-label">公司地址：</span><span class="kv-value">{{ company?.seAddress
                      }}</span>
                  </div>
                  <div class="kv col-2"><span class="kv-label">公司简介：</span><span class="kv-value">{{
                    company?.seFoundedTime
                  }}</span>
                  </div>
                </div>

              </div>

              <!-- 屠宰企业照片上传区域 -->
              <div class="section mt16">
                <div class="section-head">
                  <span class="blue-bar" />
                  <span>企业照片</span>
                </div>
                <el-upload class="uploader mt8" action="#" list-type="picture-card"
                  v-model:file-list="processCompanyPhotos" :http-request="(o) => uploadImage(o, 'processCompanyPhotos')"
                  :on-remove="(f, l) => onRemove(f, l, 'processCompanyPhotos')" :limit="MAX_IMAGES"
                  :on-exceed="onExceed">
                  <el-icon>
                    <Plus />
                  </el-icon>
                  <template #file="{ file }">
                    <div class="upload-card">
                      <img class="upload-card-img" :src="file.url" alt="" />
                      <button class="delete-badge" @click.stop="removeFile('inspect', file, file.name)">×</button>
                    </div>
                  </template>
                </el-upload>
              </div>
            </el-tab-pane>

            <el-tab-pane label="深加工信息" name="process">
              <div class="section">
                <div class="section-head">
                  <span style="color:dodgerblue; font-size: 18px; font-weight: bold;">深加工信息</span>
                  <button class="pill-button" @click="openProcessTeamDialog">设置</button>

                </div>

                <div class="kv-grid">

                  <div class="kv"><span class="kv-label">班组：</span><span class="kv-value">{{ process?.processingTeam
                      }}</span>
                  </div>
                  <div class="kv"><span class="kv-label">负责人：</span><span class="kv-value">{{ process?.processingName
                      }}</span>
                  </div>
                </div>
              </div>

              <!-- 食品安全信息上传区域 -->
              <div class="section mt16">
                <div class="section-head">
                  <span style="color:dodgerblue; font-size: 18px; font-weight: bold;">食品安全信息</span>
                </div>
                <el-upload class="uploader mt8" action="#" list-type="picture-card" v-model:file-list="foodSafetyPhotos"
                  :http-request="(o) => uploadImage(o, 'foodSafety')"
                  :on-remove="(f, l) => onRemove(f, l, 'foodSafety')" :limit="MAX_IMAGES" :on-exceed="onExceed">
                  <el-icon>
                    <Plus />
                  </el-icon>
                  <template #file="{ file }">
                    <div class="upload-card">
                      <img class="upload-card-img" :src="file.url" alt="" />
                      <div class="img-bottom-label">{{ file.label || '制度/报告' }}</div>
                      <button class="delete-badge" @click.stop="removeFile('inspect', file, file.name)">×</button>
                    </div>
                  </template>
                </el-upload>
              </div>

              <!-- 供应商信息  -->
              <div class="section mt16">
                <div class="section-head">
                  <span style="color:dodgerblue; font-size: 18px; font-weight: bold;">供应商信息</span>

                </div>
                <div class="section mt16">
                  <div class="section-head">
                    <span class="blue-bar" />
                    <span>原料</span>
                    <button class="pill-button" @click="openSupplierDialog">设置</button>
                  </div>
                </div>

                <div class="kv-grid">

                  <div class="kv col-2"><span class="kv-label">生产批次：</span><span class="kv-value">{{ product?.basicBatch

                      }}</span>
                  </div>
                </div>
                <!-- 原料相关材料上传区域 -->
                <div class="section-head mt12">
                  <span class="blue-bar" />
                  <span>相关材料</span>
                </div>
                <el-upload class="uploader mt8" action="#" list-type="picture-card" v-model:file-list="rawMaterialDocs"
                  :http-request="(o) => uploadImage(o, 'rawDocs')" :on-remove="(f, l) => onRemove(f, l, 'rawDocs')"
                  :limit="MAX_IMAGES" :on-exceed="onExceed">
                  <el-icon>
                    <Plus />
                  </el-icon>
                  <template #file="{ file }">
                    <div class="upload-card">
                      <img class="upload-card-img" :src="file.url" alt="" />
                      <div class="img-bottom-label">{{ file.label || '材料' }}</div>
                      <button class="delete-badge" @click.stop="removeFile('inspect', file, file.name)">×</button>
                    </div>
                  </template>
                </el-upload>
              </div>

              <!-- 辅料 -->
              <div class="section mt16">
                <div class="section-head">
                  <span class="blue-bar" />
                  <span>辅料</span>
                  <button class="pill-button" @click="openSupplierDialog">设置</button>
                </div>
                <div class="kv-grid">
                  <div class="kv col-2"><span class="kv-label">生产批次：</span><span class="kv-value">{{ product?.basicBatch
                      }}</span>
                  </div>
                </div>
                <div class="section-head mt12">
                  <span class="blue-bar" />
                  <span>相关材料</span>
                </div>
                <el-upload class="uploader mt8" action="#" list-type="picture-card" v-model:file-list="auxMaterialDocs"
                  :http-request="(o) => uploadImage(o, 'auxDocs')" :on-remove="(f, l) => onRemove(f, l, 'auxDocs')"
                  :limit="MAX_IMAGES" :on-exceed="onExceed">
                  <el-icon>
                    <Plus />
                  </el-icon>
                  <template #file="{ file }">
                    <div class="upload-card">
                      <img class="upload-card-img" :src="file.url" alt="" />
                      <div class="img-bottom-label">{{ file.label || '材料' }}</div>
                      <button class="delete-badge" @click.stop="removeFile('inspect', file, file.name)">×</button>
                    </div>
                  </template>
                </el-upload>
              </div>

              <!-- 添加剂 -->
              <div class="section mt16">
                <div class="section-head">
                  <span class="blue-bar" />
                  <span>添加剂</span>
                  <button class="pill-button" @click="openSupplierDialog">设置</button>
                </div>
                <div class="kv-grid">
                  <div class="kv col-2"><span class="kv-label">生产批次：</span><span class="kv-value">{{ product?.basicBatch
                      }}</span>
                  </div>
                </div>
                <!-- 添加剂相关材料上传区域 -->
                <div class="section-head mt12">
                  <span class="blue-bar" />
                  <span>相关材料</span>
                </div>
                <el-upload class="uploader mt8" action="#" list-type="picture-card" v-model:file-list="additiveDocs"
                  :http-request="(o) => uploadImage(o, 'additiveDocs')"
                  :on-remove="(f, l) => onRemove(f, l, 'additiveDocs')" :limit="MAX_IMAGES" :on-exceed="onExceed">
                  <el-icon>
                    <Plus />
                  </el-icon>
                  <template #file="{ file }">
                    <div class="upload-card">
                      <img class="upload-card-img" :src="file.url" alt="" />
                      <div class="img-bottom-label">{{ file.label || '材料' }}</div>
                      <button class="delete-badge" @click.stop="removeFile('inspect', file, file.name)">×</button>
                    </div>
                  </template>
                </el-upload>

              </div>

              <!-- 包材 -->
              <div class="section mt16">
                <div class="section-head">
                  <span class="blue-bar" />
                  <span>包材</span>
                  <button class="pill-button" @click="openSupplierDialog">设置</button>
                </div>
                <div class="kv-grid">
                  <div class="kv col-2"><span class="kv-label">生产批次：</span><span class="kv-value">{{ product?.basicBatch
                      }}</span>
                  </div>
                </div>
                <!-- 包材相关材料上传区域 -->
                <div class="section-head mt12">
                  <span class="blue-bar" />
                  <span>相关材料</span>
                </div>
                <el-upload class="uploader mt8" action="#" list-type="picture-card" v-model:file-list="packageDocs"
                  :http-request="(o) => uploadImage(o, 'packageDocs')"
                  :on-remove="(f, l) => onRemove(f, l, 'packageDocs')" :limit="MAX_IMAGES" :on-exceed="onExceed">
                  <el-icon>
                    <Plus />
                  </el-icon>
                  <template #file="{ file }">
                    <div class="upload-card">
                      <img class="upload-card-img" :src="file.url" alt="" />
                      <div class="img-bottom-label">{{ file.label || '材料' }}</div>
                      <button class="delete-badge" @click.stop="removeFile('inspect', file, file.name)">×</button>
                    </div>
                  </template>
                </el-upload>
              </div>

              <!-- 深加工企业信息（仅显示 名称/许可证） -->
              <div class="section mt16">
                <div class="section-head">
                  <span style="color:dodgerblue; font-size: 18px; font-weight: bold;">企业信息</span>
                  <button class="pill-button" @click="openCompanyDialog">设置</button>
                </div>
                <div class="kv-grid">
                  <div class="kv"><span class="kv-label">公司名称：</span><span class="kv-value">{{
                    processcompany?.companyName
                      }}</span>
                  </div>
                  <div class="kv"><span class="kv-label">生产许可证号：</span><span class="kv-value">{{
                    processcompany?.companyLicense
                      }}</span></div>
                </div>
              </div>

              <!-- 加工企业照片上传区域 -->
              <div class="section mt16">
                <div class="section-head">
                  <span style="color:dodgerblue; font-size: 18px; font-weight: bold;">企业照片</span>
                </div>
                <el-upload class="uploader mt8" action="#" list-type="picture-card"
                  v-model:file-list="processEnterprisePhotos"
                  :http-request="(o) => uploadImage(o, 'processEnterprisePhotos')"
                  :on-remove="(f, l) => onRemove(f, l, 'processEnterprisePhotos')" :limit="MAX_IMAGES"
                  :on-exceed="onExceed">
                  <el-icon>
                    <Plus />
                  </el-icon>
                  <template #file="{ file }">
                    <div class="upload-card">
                      <img class="upload-card-img" :src="file.url" alt="" />
                      <button class="delete-badge" @click.stop="removeFile('inspect', file, file.name)">×</button>
                    </div>
                  </template>
                </el-upload>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>

      </el-col>
    </el-row>

    <!-- 弹窗：养殖信息 -->
    <el-dialog v-model="breedDialogVisible" title="养殖信息" width="520px">
      <el-form :model="breedForm" :rules="breedRules" ref="breedFormRef" label-width="120px">
        <el-form-item label="品种" prop="cultivationVariety">
          <el-input v-model="breedForm.cultivationVariety" maxlength="30" show-word-limit />
        </el-form-item>
        <el-form-item label="来源" prop="cultivationSource">
          <el-input v-model="breedForm.cultivationSource" maxlength="30" show-word-limit />
        </el-form-item>
        <el-form-item label="饲养天数" prop="cultivationDays">
          <el-input v-model="breedForm.cultivationDays" maxlength="5" />
        </el-form-item>
        <el-form-item label="饲料品牌" prop="cultivationBrand">
          <el-input v-model="breedForm.cultivationBrand" maxlength="30" show-word-limit />
        </el-form-item>
        <el-form-item label="饲养负责人" prop="cultivationLeader">
          <el-input v-model="breedForm.cultivationLeader" maxlength="30" show-word-limit />
        </el-form-item>
        <el-form-item label="出栏日期" prop="cultivationOutDate">
          <el-date-picker v-model="breedForm.cultivationOutDate" type="date" value-format="YYYY-MM-DD" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="breedDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveBreed(breed?.id)">保存</el-button>
      </template>
    </el-dialog>

    <!-- 弹窗：屠宰信息 -->
    <el-dialog v-model="slaughterDialogVisible" title="屠宰信息" width="520px">

      <el-form :model="slaughterForm" :rules="slaughterRules" ref="slaughterFormRef" label-width="160px">
        <el-form-item label="批次" prop="slaughterBatch">
          <el-input v-model="slaughterForm.slaughterBatch" />
        </el-form-item>
        <el-form-item label="到厂均重（公斤）" prop="slaughterWeight">
          <el-input-number v-model="slaughterForm.slaughterWeight" :min="0" :max="9999" />
        </el-form-item>
        <!-- 到达时间 -->
        <el-form-item label="到厂时间" prop="arrivaltime">
          <el-date-picker v-model="slaughterForm.arrivaltime" type="datetime" placeholder="选择日期+时分秒"
            value-format="YYYY-MM-DDTHH:mm:ss"></el-date-picker>
        </el-form-item>

        <!-- 屠宰时间 -->
        <el-form-item label="屠宰时间" prop="slaughtertime">
          <el-date-picker v-model="slaughterForm.slaughtertime" type="datetime" placeholder="选择日期+时分秒"
            value-format="YYYY-MM-DDTHH:mm:ss"></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="slaughterDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveSlaughter(slaughter?.id)">保存</el-button>
      </template>
    </el-dialog>

    <!-- 弹窗：企业信息（养殖场） -->
    <el-dialog v-model="farmDialogVisible" title="企业信息" width="520px">
      <el-form :model="farmForm" :rules="farmRules" ref="farmFormRef" label-width="120px">
        <el-form-item label="养殖场" prop="enterpriseFarms">
          <el-input v-model="farmForm.enterpriseFarms" maxlength="30" show-word-limit />
        </el-form-item>
        <el-form-item label="负责人" prop="enterpriseLeader">
          <el-input v-model="farmForm.enterpriseLeader" maxlength="30" show-word-limit />
        </el-form-item>
        <el-form-item label="存栏数量（只）" prop="enterpriseNum">
          <el-input v-model="farmForm.enterpriseNum" maxlength="5" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="farmDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveFarm(farmInfo?.id)">保存</el-button>
      </template>
    </el-dialog>

    <!-- 弹窗：深加工班组信息 -->
    <el-dialog v-model="processDialogVisible" title="深加工信息" width="520px">
      <el-form :model="processForm" :rules="processformRules" ref="processFormRef" label-width="120px">
        <el-form-item label="班组" prop="processingTeam">
          <el-input v-model="processForm.processingTeam" />
        </el-form-item>
        <el-form-item label="负责人" prop="processingName">
          <el-input v-model="processForm.processingName" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="processDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveProcessTeam(process?.id)">保存</el-button>
      </template>
    </el-dialog>
    <!-- 弹窗：深加工企业信息 -->
    <el-dialog v-model="CompanyDialogVisible" title="企业信息" width="520px">
      <el-form :model="CompanyForm" :rules="CompanyRules" ref="CompanyFormRef" label-width="120px">
        <el-form-item label="公司名称" prop="companyName">
          <el-input v-model="CompanyForm.companyName" />
        </el-form-item>
        <el-form-item label="生产许可证号" prop="companyLicense">
          <el-input v-model="CompanyForm.companyLicense" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="CompanyDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveCompany(processcompany?.id)">保存</el-button>
      </template>
    </el-dialog>
    <!-- 弹窗：屠宰 - 企业信息设置 -->
    <el-dialog v-model="processCompanyDialogVisible" title="企业信息" width="520px">

      <el-form :model="processCompanyForm" :rules="processCompanyRules" ref="processCompanyFormRef" label-width="120px">
        <el-form-item label="公司名称" prop="slaughterName">
          <el-input v-model="processCompanyForm.slaughterName" maxlength="30" show-word-limit />
        </el-form-item>
        <el-form-item label="公司地址" prop="seAddress">
          <div id="app">
            <el-cascader size="large" :options="pcaTextArr" v-model="processCompanyForm.seAddress">
            </el-cascader>
          </div>
        </el-form-item>
        <el-form-item label="成立时间" prop="time">
          <el-date-picker v-model="processCompanyForm.time" type="date" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="公司简介" prop="seFoundedTime">
          <el-input v-model="processCompanyForm.seFoundedTime" type="textarea" :rows="4" maxlength="500"
            show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="processCompanyDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveProcessCompany(company?.id)">保存</el-button>
      </template>
    </el-dialog>

    <!-- 弹窗：供应商原料信息 -->
    <el-dialog v-model="supplierDialogVisible" title="供应商信息-原料" width="520px">
      <el-form :model="supplierForm" label-width="120px">
        <el-form-item label="生产批次" required>
          <el-input v-model="supplierForm.batch" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="supplierDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveSupplier(supplier?.id)">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// 引入Vue相关API：ref用于创建响应式基本类型，reactive用于创建响应式对象，onMounted用于组件挂载后执行
import { ref, reactive, onMounted } from 'vue'
// 引入Element Plus图标：Plus图标用于上传等按钮
import { Plus } from '@element-plus/icons-vue'
// 引入Element Plus消息提示组件：用于显示操作结果提示
import { ElMessage, ElMessageBox } from 'element-plus'
// 引入自定义axios实例：用于发送网络请求
import myaxios from '@/Http/RabbitHelp'
// 引入路由相关API：用于获取当前路由信息和路由跳转
import { useRoute, useRouter } from 'vue-router'
import {
  provinceAndCityData,
  pcTextArr,
  regionData,
  pcaTextArr,
  codeToText,
} from "element-china-area-data";

import moment from 'moment'
const router = useRouter()
const route = useRoute()
// 活跃标签页：默认选中'breed'标签页（养殖信息）
const activeTab = ref('breed')
const basicId = reactive({
  basicId: route.query.id
})
// 商品基本数据：存储商品的各类溯源信息，包括批次、有效期、许可证、企业信息等
const product = ref({
  "basicId": null,
  "goodsId": null,
  "basicBatch": "",
  "basicExpiration": null,
  "basicLicense": "",
  "basicEnterprise": "",
  "basicPhoto": "",
  "goodsName": "",
  "outPutNum": null,
  "processingTeam": "",
  "processingName": "",
  "companyName": "",
  "companyLicense": "",
  "cultivationVariety": "",
  "cultivationSource": "",
  "cultivationDays": null,
  "enterpriseFarms": "",
  "enterpriseLeader": "",
  "healthDays": null,
  "healthWay": "",
  "healthAction": "",
  "imgUrl": null,
  "imgType": "",
  "slaughterBatch": "",
  "arrivaltime": null,
  "slaughterWeight": null,
  "seAddress": null,
  "seFoundedTime": null
})

const inspectFileList = ref([])
const certFileList = ref([])
const companyFileList = ref([])
// 屠宰相关图片：检疫和质检图片
const slaughterCertList = ref([])
// 加工厂照片
const processCompanyPhotos = ref([])
// 深加工相关图片：食品安全制度、抽检报告等
const foodSafetyPhotos = ref([])
// 原料相关文件：检验报告、进厂验收、供应商资质等
const rawMaterialDocs = ref([])
const auxMaterialDocs = ref([]) // 辅助材料文件列表
const additiveDocs = ref([]) // 添加剂文件列表
const packageDocs = ref([]) // 包装材料文件列表
// 加工企业照片
const processEnterprisePhotos = ref([])

// 完整图片URL：用于拼接图片的完整路径（基础URL+图片相对路径）
const fullImageUrl = reactive({
  fullImageUrl: ""
})

// 分页查询参数：用于请求商品溯源信息时的分页和查询条件，包含页码、页大小和商品ID（从路由参数获取）
const paging = reactive({
  "pageIndex": 1,
  "pageSize": 1,
  id: route.query.id
})

// 查询商品溯源信息：发送POST请求获取商品详情，成功后更新product数据和图片完整路径
const basicGet = () => {

  myaxios.post("/api/Goods/BasicShow", paging).then(res => {
    if (res.data.code == 200) {
      console.log(product.value)
      product.value = res.data.data.list[0]
      const baseUrl = "http://localhost:5160";
      fullImageUrl.fullImageUrl = baseUrl + product?.value.basicPhoto
    }
  })
}

const ImgGetForm = reactive({
  "basicId": route.query.id,
  "imgType": ""
})


//查询图片信息
const ImgGet = () => {
  myaxios.post("/api/Img/ImgGet", ImgGetForm).then(res => {
    if (res.data.code == 200) {

      const baseUrl = "http://localhost:5160";
      const image = res.data.data // 为空时默认空数组
      // 先清空所有文件列表，避免重复加载
      // 定义所有可能的文件列表，确保每个列表都已正确初始化
      const allFileLists = [
        inspectFileList,
        certFileList,
        companyFileList,
        slaughterCertList,
        foodSafetyPhotos,
        rawMaterialDocs,
        auxMaterialDocs,
        additiveDocs,
        packageDocs,
        processEnterprisePhotos,
        processCompanyPhotos
      ];
      // 安全清空所有文件列表（过滤掉可能的undefined）
      //Boolean提前排除掉数组中可能存在的 undefined 或 null 等无效值
      allFileLists.filter(Boolean).forEach(list => {
        if (list && list.value !== undefined) {
          list.value = [];
        }
      });

      // 遍历所有图片，按类型分别添加到对应的文件列表
      image.forEach(img => {
        // 过滤掉imgUrl为空或无效的图片
        if (!img.imgUrl || img.imgUrl.trim() === '') {
          console.warn('跳过无效图片（imgUrl为空）', img);
          return;
        }
        const targetFileList = getTargetList(img.imgType);
        if (targetFileList) {
          targetFileList.value.push({
            url: baseUrl + img.imgUrl,
            name: `${img.id}`,
            // uid: `img-${img.id}`, // 用后端返回的id生成唯一标识
            // id: img.id, // 保留后端id，用于删除操作
            imgType: img.imgType // 保留类型信息
          });
        } else {
          console.warn(`未处理的图片类型: ${img.imgType}`, img);
        }
      });
    }
  })
}
// 养殖场企业信息：存储养殖场名称、负责人、存栏数量（仅展示和弹窗编辑用）
const farmInfo = ref([
])
//查询养殖企业信息溯源
const enterpriseGet = async () => {

  myaxios.post("/api/CultivationInfo/EnterGet", basicId).then(res => {
    if (res.data.code == 200) {
      farmInfo.value = res.data.data[0]


    }

  })

}


// 养殖信息
const breed = ref([])

//查询养殖信息溯源
const CultivationGet = async () => {

  myaxios.post("/api/CultivationInfo/CultivationGet", basicId).then(res => {
    if (res.data.code == 200) {
      breed.value = res.data.data[0]


    }

  })

}

// 屠宰信息：存储批次、平均重量、到厂时间、屠宰时间等
const slaughter = ref([])

//查询养殖信息溯源
const slaughterGet = async () => {

  myaxios.post("/api/Slaughter/SlaughterGet", basicId).then(res => {
    if (res.data.code == 200) {
      slaughter.value = res.data.data[0]


    }

  })

}

// 加工信息：存储生产班组和负责人
const process = ref([])
//查询深加工信息溯源
const processGet = async () => {

  myaxios.post("/api/Process/ProcessGet", basicId).then(res => {
    if (res.data.code == 200) {
      process.value = res.data.data[0]


    }

  })

}


// 供应商信息：存储供应商批次
const supplier = reactive({
  batch: '20120718'
})
//图片信息添加
const imgForm = reactive({
  "basicId": route.query.id,
  "imgUrl": "",
  "imgType": "",
  "basicBatch": route.query.basicBatch

})

// 添加图片信息
const imgSave = () => {


  myaxios.post("/api/Img/ImgAdd", imgForm).then(res => {
    if (res.data.code == 200) {

      ElMessage.success('图片上传成功')
      ImgGet()

    } else {
      ElMessage.error("图片上传失败")
    }

  })

}







// 图片上传列表：各类图片的初始数据（检验图片、资质图片、企业图片等）

// 最大图片上传数量限制：全局限制最多上传9张图片
const MAX_IMAGES = 9
// 图片超出数量提示：当上传数量超过MAX_IMAGES时显示警告
function onExceed() { ElMessage.warning(`最多只能上传 ${MAX_IMAGES} 张图片`) }





// 获取目标文件列表：根据类型返回对应的图片列表（用于统一处理不同类型的图片上传/删除）
function getTargetList(type) {
  return type === 'inspect'
    ? inspectFileList
    : type === 'cert'
      ? certFileList
      : type === 'company'
        ? companyFileList
        : type === 'slaughterCert'
          ? slaughterCertList
          : type === 'foodSafety'
            ? foodSafetyPhotos
            : type === 'rawDocs'
              ? rawMaterialDocs
              : type === 'auxDocs'
                ? auxMaterialDocs
                : type === 'additiveDocs'
                  ? additiveDocs
                  : type === 'packageDocs'
                    ? packageDocs
                    : type === 'processEnterprisePhotos'
                      ? processEnterprisePhotos
                      : processCompanyPhotos
}
/**
 * 异步图片上传函数：处理不同类型图片的上传逻辑，支持文件校验、发送请求和结果处理
 * @param {Object} options - 上传相关参数（包含文件对象、回调函数等）
 * @param {string} type - 图片类型标识（用于区分不同上传场景，如检验报告、企业照片等）
 */


// 上传图片：处理不同类型图片的上传逻辑，通过FormData提交文件，成功后更新对应图片列表
const uploadImage = async (options, type) => {

  // 从options中解构出关键参数：
  // file：待上传的文件对象

  const { file } = options
  // 创建FormData对象，用于包装文件数据（符合multipart/form-data格式要求）
  const formData = new FormData()
  // 将文件添加到FormData中，后端通过'imageFile'字段接收
  formData.append('imageFile', file)
  // 根据图片类型获取对应的文件列表（如检验报告列表、资质列表等）
  const target = getTargetList(type)

  // 发送上传请求

  const res = await myaxios.post("/api/Img/Upload/upload", formData)
  if (res.data.success) {
    // 根据类型更新对应表单的图片地址



    const url = res.data.url
    // 2. 上传成功后，按照历史数据格式构造对象

    const baseUrl = "http://localhost:5160";

    target.value.push() // 上传成功后添加到列表

    imgForm.imgUrl = url
    imgForm.imgType = type
    //一个添加方法
    imgSave()


  } else {
    ElMessage.error('图片上传失败')
  }


}


/**
 * 移除指定类型文件列表中的特定文件
 * @param {string} type - 文件类型标识（用于区分不同的文件列表，如检验报告、企业照片等）
 * @param {Object} file - 要移除的文件对象（包含uid或url等唯一标识）
 */
// 手动移除文件：根据类型和文件信息从列表中删除指定图片
async function removeFile(type, file, name) {

  // 显示确认对话框，防止误操作
  if (!confirm('确定要删除这张图片吗？')) {
    return;
  }

  // 根据文件类型获取对应的文件列表（如检验报告列表、资质文件列表等）
  // 例如type为'inspect'时，target可能指向inspectFileList
  const target = getTargetList(type);
  // 从列表中移除对应的文件
  const index = target.value.findIndex(item => item.name === name);
  if (index !== -1) {

    myaxios.post("/api/Img/ImgDel", { id: name }).then(res => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.message)
        target.value.splice(index, 1);
      } else {
        ElMessage.error(res.data.message)
      }
    })
  }

}


// 养殖信息弹窗相关：控制弹窗显示状态、表单引用和表单数据
const breedDialogVisible = ref(false) // 弹窗显示状态
const breedFormRef = ref() // 表单引用（用于校验）
const breedForm = reactive({
  "cultivationVariety": "",
  "cultivationSource": "",
  "cultivationDays": 0,
  "cultivationBrand": "",
  "cultivationLeader": "",
  "cultivationOutDate": "",
  "basicId": route.query.id
}) // 表单数据

// 养殖信息表单验证规则：校验必填项、格式（中文/字母/数字）、长度限制等
const nameLikePattern = /^[\u4e00-\u9fa5A-Za-z0-9]+$/ // 中文、字母、数字正则
const numberPattern = /^\d{1,5}$/ // 1-5位数字正则
const breedRules = {
  brand: [
    { required: true, message: '请填写品种', trigger: 'blur' },
    { pattern: nameLikePattern, message: '只能输入中文、字母或数字，且不含标点', trigger: 'blur' },
    { min: 1, max: 30, message: '最多输入30位字符', trigger: 'blur' }
  ],
  source: [
    { required: true, message: '请填写来源', trigger: 'blur' },
    { pattern: nameLikePattern, message: '只能输入中文、字母或数字，且不含标点', trigger: 'blur' },
    { min: 1, max: 30, message: '最多输入30位字符', trigger: 'blur' }
  ],
  shelfDays: [
    { required: true, message: '请填写饲养天数', trigger: 'blur' },
    { pattern: numberPattern, message: '只能输入数字，最多5位', trigger: 'blur' }
  ],
  feedBrand: [
    { required: true, message: '请填写饲料品牌', trigger: 'blur' },
    { pattern: nameLikePattern, message: '只能输入中文、字母或数字，且不含标点', trigger: 'blur' },
    { min: 1, max: 30, message: '最多输入30位字符', trigger: 'blur' }
  ],
  owner: [
    { required: true, message: '请填写饲养负责人', trigger: 'blur' },
    { pattern: nameLikePattern, message: '只能输入中文、字母或数字，且不含标点', trigger: 'blur' },
    { min: 1, max: 30, message: '最多输入30位字符', trigger: 'blur' }
  ],
  outDate: [
    { required: true, message: '请选择出栏日期', trigger: 'change' }
  ]
}

// 打开养殖信息弹窗：将当前养殖信息赋值给表单，显示弹窗
function openBreedDialog() {


  Object.assign(breedForm, breed.value);
  breedDialogVisible.value = true;

}

// 保存养殖信息：校验表单，通过后更新养殖信息，关闭弹窗并提示成功
function saveBreed(id) {
  breedForm.id = id
  breedFormRef.value.validate((ok) => {
    if (!ok) {
      ElMessage.error('请完善必填项')
      return
    }
    myaxios.post("/api/CultivationInfo/CultivationAdd", breedForm).then(res => {
      if (res.data.code == 200) {
        breedDialogVisible.value = false

        Object.assign(breed.value ? breed.value : [], breedForm)
        CultivationGet()

        ElMessage.success(res.data.message)

      } else {
        ElMessage.error(res.data.message)
      }

    })



  })
}

// 屠宰企业信息：存储企业名称、许可证、地址、成立时间、简介等
const company = ref([])
//查询养殖信息溯源
const companyGet = async () => {

  myaxios.post("/api/Slaughter/SlaComGet", basicId).then(res => {
    if (res.data.code == 200) {
      company.value = res.data.data[0]


    }

  })

}

// 深加工企业信息：
const processcompany = ref([])
//查询养殖信息溯源
const processcompanyGet = async () => {

  myaxios.post("/api/Process/ProcessComGet", basicId).then(res => {
    if (res.data.code == 200) {
      processcompany.value = res.data.data[0]


    }

  })

}
// 深加工企业信息弹窗相关：控制弹窗显示状态、表单引用、表单数据和验证规则
const CompanyDialogVisible = ref(false) // 弹窗显示状态
const CompanyFormRef = ref() // 表单引用（用于校验）
const CompanyForm = reactive({
  "id": 0,
  "companyName": "",
  "companyLicense": "",
  "basicId": route.query.id
}) // 表单数据

// 深加工企业信息验证规则：
const CompanyRules = {
  companyName: [
    { required: true, message: '请填写公司名称', trigger: 'blur' },
    {
      pattern: /^[\u4e00-\u9fa5a-zA-Z]{1,30}$/, // 中文/字母，1-30位
      message: '仅允许中文、字母，最多30位字符'
    },
  ],
  companyLicense: [
    { required: true, message: '请填写营业执照号', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9()]{1,30}$/, // 数字、字母、括号，1-30位
      message: '仅允许数字、字母（含大小写）、括号，最多30位字符',
      trigger: 'blur'
    }

  ],
}

// 打开深加工企业信息弹窗：
function openCompanyDialog() {

  Object.assign(CompanyForm, processcompany.value ? processcompany.value : [])



  CompanyDialogVisible.value = true
}

// 保存深加工企业信息：
function saveCompany(id) {
  CompanyForm.id = id
  CompanyFormRef.value.validate((ok) => {
    if (!ok) { ElMessage.error('请完善必填项'); return }

    myaxios.post("/api/Process/ProcessComAdd", CompanyForm).then(res => {
      if (res.data.code == 200) {
        companyGet()
        CompanyDialogVisible.value = false


        Object.assign(processcompany.value ? processcompany.value : [], CompanyForm)

        ElMessage.success(res.data.message)

      } else {
        ElMessage.error(res.data.message)
      }

    })


  })



}


// 屠宰信息弹窗相关：控制弹窗显示状态和表单数据
const slaughterDialogVisible = ref(false) // 弹窗显示状态
const slaughterForm = reactive({
  "id": 0,
  "slaughterBatch": "",
  "arrivaltime": "",
  "slaughterWeight": 0,
  "slaughtertime": "",
  "basicId": route.query.id
}) // 表单数据
// 屠宰表单校验规则（核心）
const slaughterRules = {
  // 1. 屠宰批次校验：必填、中文/字母、禁止特殊字符、最多30位
  slaughterBatch: [
    { required: true, message: '屠宰批次为必填项', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z\d]{0,30}$/, message: '仅允许中文、字母，最多30位字符', trigger: 'blur' }
  ],
  // 2. 屠宰重量校验：必填、仅数字、最多5位
  slaughterWeight: [
    { required: true, message: '屠宰重量为必填项', trigger: 'blur' },
    { pattern: /^\d{1,5}$/, message: '仅允许输入数字，最多5位', trigger: 'blur' }
  ],
  // 3. 到达时间校验：必填（通过组件 + value-format 保证格式）
  arrivaltime: [
    { required: true, message: '到达时间为必填项', trigger: 'change' }
  ],
  // 4. 屠宰时间校验：必填（通过组件 + value-format 保证格式）
  slaughtertime: [
    { required: true, message: '屠宰时间为必填项', trigger: 'change' }
  ]
};

// 表单引用
const slaughterFormRef = ref();
// 打开屠宰信息弹窗：将当前屠宰信息赋值给表单，显示弹窗
function openSlaughterDialog() {
  Object.assign(slaughterForm, slaughter.value ? slaughter.value : [])
  slaughterDialogVisible.value = true
}

// 保存屠宰信息：更新屠宰信息，关闭弹窗
function saveSlaughter(id) {
  slaughterForm.id = id
  slaughterFormRef.value.validate((ok) => {
    if (!ok) {
      ElMessage.error('请完善必填项')
      return
    }
    myaxios.post("/api/Slaughter/SlaughterAdd", slaughterForm).then(res => {
      if (res.data.code == 200) {
        slaughterDialogVisible.value = false

        Object.assign(slaughter.value ? slaughter.value : [], slaughterForm)
        slaughterGet()

        ElMessage.success(res.data.message)

      } else {
        ElMessage.error(res.data.message)
      }

    })



  })



}

// 养殖场企业信息弹窗相关：控制弹窗显示状态、表单引用、表单数据和验证规则
const farmDialogVisible = ref(false) // 弹窗显示状态
const farmFormRef = ref() // 表单引用（用于校验）
// 养殖企业表单数据
const farmForm = reactive({
  "id": 0,
  "basicId": route.query.id,
  "enterpriseFarms": "",
  "enterpriseLeader": "",
  "enterpriseNum": ""
})

// 养殖场信息验证规则：校验必填项、格式、长度
const farmRules = {
  enterpriseFarms: [
    { required: true, message: '请填写养殖场', trigger: 'blur' },
    { pattern: nameLikePattern, message: '只能输入中文、字母或数字，且不含标点', trigger: 'blur' },
    { min: 1, max: 30, message: '最多输入30位字符', trigger: 'blur' }
  ],
  enterpriseLeader: [
    { required: true, message: '请填写负责人', trigger: 'blur' },
    { pattern: nameLikePattern, message: '只能输入中文、字母或数字，且不含标点', trigger: 'blur' },
    { min: 1, max: 30, message: '最多输入30位字符', trigger: 'blur' }
  ],
  enterpriseNum: [
    { required: true, message: '请填写存栏数量', trigger: 'blur' },
    { pattern: numberPattern, message: '只能输入数字，最多5位', trigger: 'blur' }
  ]
}

// 打开养殖场信息弹窗：将当前养殖场信息赋值给表单，显示弹窗
function openFarmDialog() {
  Object.assign(farmForm, farmInfo.value)

  farmDialogVisible.value = true
}

// 保存养殖场企业信息：校验表单，通过后更新养殖场信息，关闭弹窗并提示成功
function saveFarm(id) {
  farmForm.id = id
  farmFormRef.value.validate((ok) => {
    if (!ok) { ElMessage.error('请完善必填项'); return }
    myaxios.post("/api/CultivationInfo/EnterAdd", farmForm).then(res => {
      if (res.data.code == 200) {
        farmDialogVisible.value = false
        enterpriseGet()
        Object.assign(farmInfo.value ? farmInfo.value : [], farmForm)

        ElMessage.success(res.data.message)

      } else {
        ElMessage.error(res.data.message)
      }

    })


  })
}

// 深加工信息弹窗相关：控制弹窗显示状态和表单数据
const processDialogVisible = ref(false) // 弹窗显示状态
const processForm = reactive({
  "id": 0,
  "processingTeam": "",
  "processingName": "",
  "basicId": route.query.id
}) // 表单数据
// 养殖场信息验证规则：校验必填项、格式、长度
const processformRules = {
  processingTeam: [
    { required: true, message: '请填写班组', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]{1,30}$/, message: '只能输入中文、字母或数字，且不含标点,最多输入30位字符', trigger: 'blur' },

  ],
  processingName: [
    { required: true, message: '请填写负责人', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]{1,30}$/, message: '只能输入中文、字母或数字，且不含标点,最多输入30位字符', trigger: 'blur' },

  ],

}
// 打开深加工信息弹窗：将当前加工信息赋值给表单，显示弹窗
function openProcessTeamDialog() {
  Object.assign(processForm, process.value ? process.value : [])

  processDialogVisible.value = true
}


const processFormRef = ref() // 表单引用（用于校验）
// 保存深加工信息：更新加工信息，关闭弹窗
function saveProcessTeam(id) {
  processForm.id = id
  processFormRef.value.validate((ok) => {
    if (!ok) { ElMessage.error('请完善必填项'); return }

    myaxios.post("/api/Process/ProcessAdd", processForm).then(res => {
      if (res.data.code == 200) {
        processGet()
        processDialogVisible.value = false


        Object.assign(process.value ? process.value : [], processForm)

        ElMessage.success(res.data.message)

      } else {
        ElMessage.error(res.data.message)
      }

    })


  })



}

// 屠宰企业信息弹窗相关：控制弹窗显示状态、表单引用、表单数据和验证规则
const processCompanyDialogVisible = ref(false) // 弹窗显示状态
const processCompanyFormRef = ref() // 表单引用（用于校验）
const processCompanyForm = reactive({
  "id": 0,
  "slaughterName": "",
  "seAddress": "",
  "cascaderAddress": [], // 新增：绑定级联组件的数组
  "time": "",
  "seFoundedTime": "",
  "basicId": route.query.id
}) // 表单数据

// 屠宰企业信息验证规则：校验必填项、长度限制
const processCompanyRules = {
  slaughterName: [
    { required: true, message: '请填写公司名称', trigger: 'blur' },
    { min: 1, max: 30, message: '最多输入30位字符', trigger: 'blur' }
  ],
  seAddress: [
    { required: true, message: '请填写公司地址', trigger: 'blur' },

  ],
  time: [
    { required: true, message: '请选择成立时间', trigger: 'change' }
  ],
  seFoundedTime: [
    { required: true, message: '请填写公司简介', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]{0,500}$/, message: '仅允许中文、字母，最多500字符', trigger: 'blur' }

  ],
}

// 打开屠宰企业信息弹窗：将当前企业信息赋值给表单，显示弹窗
function openProcessCompanyDialog(address) {

  if (address) {
    processCompanyForm.seAddress = parseAddressToCascaderValue(address, pcaTextArr)
    processCompanyForm.seFoundedTime = company.value.seFoundedTime
    processCompanyForm.slaughterName = company.value.slaughterName
    processCompanyForm.seFoundedTime = company.value.seFoundedTime
    processCompanyForm.time = company.value.time
  }


  processCompanyDialogVisible.value = true
}
// 解析地址为级联组件的 value 数组
function parseAddressToCascaderValue(address, pcaTextArr) {
  const addressArr = address.split(','); // 按空格分割地址为省、市、区数组

  const result = [];
  let currentLevel = pcaTextArr;

  for (const addrPart of addressArr) {

    const found = currentLevel.find(item => item.label === addrPart);

    if (found) {
      result.push(found.value);
      currentLevel = found.children || [];

    } else {
      break; // 没找到对应层级，停止解析
    }
  }

  // 如果解析后的数组长度和地址分割后的长度一致，说明解析成功，否则返回空数组
  return result;

}
// 保存屠宰企业信息：校验表单，通过后更新企业信息，关闭弹窗并提示成功
function saveProcessCompany(id) {
  processCompanyForm.id = id

  processCompanyForm.seAddress = processCompanyForm.seAddress.toString()
  processCompanyFormRef.value.validate((ok) => {
    if (!ok) { ElMessage.error('请完善必填项'); return }

    myaxios.post("/api/Slaughter/SlaComAdd", processCompanyForm).then(res => {
      if (res.data.code == 200) {
        processCompanyDialogVisible.value = false
        companyGet()

        Object.assign(company.value ? company.value : [], processCompanyForm)

        ElMessage.success(res.data.message)

      } else {
        ElMessage.error(res.data.message)
      }

    })


  })




}

// 供应商信息弹窗相关：控制弹窗显示状态和表单数据
const supplierDialogVisible = ref(false) // 弹窗显示状态
const supplierForm = reactive({ batch: '' }) // 表单数据

// 打开供应商信息弹窗：将当前供应商批次赋值给表单，显示弹窗
function openSupplierDialog() {
  supplierForm.batch = supplier.batch
  supplierDialogVisible.value = true
}

// 保存供应商信息：更新供应商批次，关闭弹窗
function saveSupplier(id) {
  supplierForm.id = id
  supplier.batch = supplierForm.batch
  supplierDialogVisible.value = false
}




// 保健信息表格相关
const healthList = ref([])
//查询保健信息溯源
const healthGet = async () => {

  myaxios.post("/api/CultivationInfo/HealthGet", basicId).then(res => {
    if (res.data.code == 200) {
      healthList.value = res.data.data


    }

  })

}


// 添加保健信息行：新增一行可编辑的保健信息（标记为新行）
function addHealthRow() {
  healthList.value.push({
    id: 0, "days": 0,
    "healthWay": "",
    "healthAction": "",
    "basicId": route.query.id,
    editing: true,
    _isNew: true,
    edit: {
      id: 0, "healthWay": "",
      "healthAction": "",
      "basicId": route.query.id,
      "days": 0,
    }
  })
}

// 编辑保健信息行：进入编辑状态，保存当前数据到临时编辑对象
function editHealthRow(index) {
  const row = healthList.value[index]
  row.editing = true
  row.edit = { id: row.id, days: String(row.days), healthWay: row.healthWay, healthAction: row.healthAction, basicId: row.basicId }
}

// 校验保健信息：验证饲养天数（数字）、保健类型和方式（格式和长度）
function validateHealth(edit) {
  if (!numberPattern.test(String(edit.days || ''))) {
    ElMessage.error('饲养天数只能为1-5位数字')
    return false
  }
  if (!nameLikePattern.test(edit.healthWay || '') || (edit.healthWay || '').length > 30) {
    ElMessage.error('保健方式仅限中文/字母/数字，最多30位')
    return false
  }
  if (!nameLikePattern.test(edit.healthAction || '') || (edit.healthAction || '').length > 30) {
    ElMessage.error('保健方法仅限中文/字母/数字，最多30位')
    return false
  }
  return true
}

// 保存保健信息行：校验通过后更新数据，退出编辑状态，移除新行标记并提示成功
function saveHealthRow(index, row) {
  // const row = healthList.value[index]



  const edit = row.edit || { days: String(row.days), healthWay: row.healthWay, healthAction: row.healthAction, basicId: row.basicId, id: row.id }
  console.log(edit);

  if (!validateHealth(edit)) return
  // 准备提交到后端的数据
  const submitData = {
    days: edit.days,
    healthWay: edit.healthWay,
    healthAction: edit.healthAction,
    basicId: edit.basicId,
    id: edit.id
  };
  console.log(submitData)
  myaxios.post("/api/CultivationInfo/HealthAdd", submitData).then(res => {
    if (res.data.code == 200) {
      // 更新本地数据
      row.days = Number(edit.days)
      row.healthWay = edit.healthWay
      row.healthAction = edit.healthAction
      row.id = edit.id
      row.editing = false
      delete row._isNew



      ElMessage.success(res.data.message)

    } else {
      ElMessage.error(res.data.message)
    }

  })


}

// 取消保健信息编辑：如果是新行则删除，否则退出编辑状态
function cancelHealthRow(index) {
  const row = healthList.value[index]
  if (row._isNew) {
    healthList.value.splice(index, 1)
  } else {
    row.editing = false
  }
}

// 删除保健信息行：从列表中移除指定行
function removeHealthRow(index, id) {


  ElMessageBox.confirm('确认删除保健信息？', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      myaxios.post("/api/CultivationInfo/HealthDel", { id }).then(res => {
        if (res.data.code == 200) {

          ElMessage.success(res.data.message)
          healthList.value.splice(index, 1)
        } else {
          ElMessage.error(res.data.message)
        }

      })

    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })
}

// 组件挂载后执行：加载商品溯源信息
onMounted(() => {
  basicGet()
  ImgGet()
  CultivationGet()
  healthGet()
  enterpriseGet()
  slaughterGet()
  companyGet()
  processGet()
  processcompanyGet()
})
</script>

<style scoped>
/* 页面基础样式：设置页面内边距 */
.traceable-page {
  padding: 8px 0;
}

/* 间距类：设置不同方向的外边距 */
.mb16 {
  margin-bottom: 16px;
}

.mt16 {
  margin-top: 16px;
}

.mt12 {
  margin-top: 12px;
}

.mt8 {
  margin-top: 8px;
}

/* 头部卡片样式：调整卡片内边距 */
.header-card :deep(.el-card__body) {
  padding: 20px;
}

/* 头部容器样式：flex布局，相对定位 */
.header-wrap {
  display: flex;
  position: relative;
}

/* 头部操作区样式：绝对定位在右侧，flex布局 */
.header-actions {
  position: absolute;
  right: 16px;
  top: 8px;
  display: flex;
  gap: 12px;
}

/* 幽灵按钮样式：浅灰色背景，边框，圆角 */
.ghost-button {
  background: #f6f7f8;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 8px 14px;
  cursor: pointer;
  color: #303133;
}

.ghost-button:hover {
  background: #eef1f5;
  /* hover状态背景色 */
}

/* 封面图样式：固定宽高和圆角 */
.cover {
  width: 220px;
  height: 220px;
  border-radius: 6px;
  overflow: hidden;
}

/* 元信息容器样式：flex占满剩余空间，左侧间距 */
.meta {
  flex: 1;
  margin-left: 16px;
}

/* 标题行样式：flex布局，允许换行 */
.title-row {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

/* 标题样式：字体大小和粗细 */
.title {
  margin: 0 8px 8px 0;
  font-size: 28px;
  font-weight: 700;
}

/* 副标题样式：颜色和字体大小 */
.sub {
  color: #606266;
  font-size: 12px;
}

/* 分割线样式：蓝色细条 */
.divider {
  height: 3px;
  background: #409EFF;
  opacity: .8;
}

/* 顶部元信息网格：两列布局，列间距和行间距 */
.header-meta-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  column-gap: 80px;
  row-gap: 8px;
}

/* 键值对样式：flex布局，标签和值的样式 */
.header-meta-grid .kv {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.header-meta-grid .kv .kv-label {
  color: #909399;
  /* 标签灰色 */
  min-width: 96px;
}

.header-meta-grid .kv .kv-value {
  color: #303133;
  /* 值深色 */
}

/* 主体卡片样式：调整内边距 */
.body-card :deep(.el-card__body) {
  padding: 0 16px 16px;
}

/* 区块样式：白色背景 */
.section {
  background: #fff;
}

/* 区块头部样式：flex布局，标题样式 */
.section-head {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}

.section-head.inline {
  gap: 6px;
  /* 紧凑布局的头部 */
}

/* 蓝色小条样式：用于区块头部的标识 */
.blue-bar {
  width: 4px;
  height: 14px;
  background: #409EFF;
  border-radius: 2px;
  display: inline-block;
}

/* 网格布局：行间距 */
.grid {
  display: grid;
  row-gap: 12px;
}

.grid.two-col {
  grid-template-columns: repeat(2, 1fr);
  /* 两列网格 */
  column-gap: 24px;
}

/* 字段样式：字体大小和颜色 */
.field {
  color: #303133;
  font-size: 14px;
}

.field.col-2 {
  grid-column: span 2;
  /* 跨两列的字段 */
}

.field>label {
  color: #909399;
  /* 标签灰色 */
  margin-right: 8px;
}

/* 养殖信息键值网格：两列布局，间距设置 */
.kv-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  column-gap: 80px;
  row-gap: 14px;
  margin-top: 8px;
}

/* 键值对通用样式：flex布局，标签和值的样式 */
.kv {
  display: flex;
  align-items: center;
  font-size: 16px;
  color: #303133;
}

.kv-label {
  color: #909399;
  /* 标签灰色 */
  margin-right: 12px;
  min-width: 88px;
}

.kv-value {
  color: #303133;
  /* 值深色 */
  font-weight: 500;
}

.kv.col-2 {
  grid-column: span 2;
  /* 跨两列的键值对 */
}

/* 简介区块样式：颜色和行高 */
.intro-block {
  margin-top: 8px;
  color: #606266;
  line-height: 1.8;
}

/* 侧边卡片样式：粘性定位（滚动时固定在顶部） */
.side-card {
  position: sticky;
  top: 8px;
}

/* 侧边标题样式：字体粗细 */
.side-title {
  font-weight: 600;
}

/* 侧边分割线样式：灰色细条 */
.side-divider {
  height: 3px;
  background: #dcdfe6;
  margin: 8px 0 12px;
}

/* 引导列表样式：移除默认列表样式 */
.guide-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.guide-list li {
  display: flex;
  gap: 8px;
  align-items: flex-start;
  padding: 8px 0;
  border-bottom: 1px dashed #e4e7ed;
  /* 虚线分隔 */
}

.guide-list .num {
  width: 22px;
  height: 22px;
  background: #909399;
  color: #fff;
  border-radius: 50%;
  /* 圆形数字 */
  display: inline-flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  flex: 0 0 22px;
  /* 固定大小 */
}

.guide-list .text {
  color: #606266;
  line-height: 1.5;
}

/* 上传组件样式：调整上传按钮和图片列表项大小 */
.uploader :deep(.el-upload--picture-card) {
  width: 120px;
  height: 120px;
}

.uploader :deep(.el-upload-list__item) {
  width: 120px;
  height: 120px;
}

/* 上传卡片样式：固定大小和圆角 */
.upload-card {
  position: relative;
  width: 120px;
  height: 120px;
  border-radius: 6px;
  overflow: hidden;
}

.upload-card-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  /* 图片覆盖填充 */
  display: block;
}

/* 图片底部标签：绝对定位在底部，蓝色半透明背景 */
.img-bottom-label {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(64, 158, 255, .9);
  color: #fff;
  text-align: center;
  font-size: 12px;
  padding: 4px 0;
}

/* 删除徽章样式：右上角圆形删除按钮 */
.delete-badge {
  position: absolute;
  top: -6px;
  right: -6px;
  width: 26px;
  height: 26px;
  border-radius: 50%;
  background: #fff;
  border: 1px solid #dcdfe6;
  color: #000;
  font-size: 16px;
  line-height: 24px;
  text-align: center;
  cursor: pointer;
  box-shadow: 0 1px 2px rgba(0, 0, 0, .08);
  /* 轻微阴影 */
}

.delete-badge:hover {
  background: #f5f7fa;
  /* hover状态背景色 */
}

/*  pills风格按钮：用于设置/新增行，圆角浅色背景 */
.pill-button {
  border: none;
  background: #f2f3f5;
  color: #303133;
  border-radius: 16px;
  padding: 6px 16px;
  cursor: pointer;
  font-size: 14px;
}

.pill-button:hover {
  background: #e9ebef;
  /* hover状态背景色 */
}
</style>
